package com.zyd.module.api.controller;

import com.zyd.common.util.IpUtil;
import com.zyd.common.util.R;
import com.zyd.common.util.RandomUtils;
import com.zyd.enums.GlobalConstant;
import com.zyd.module.admin.model.CustomerEntity;
import com.zyd.module.admin.service.CustomerService;
import com.zyd.module.admin.service.RedisService;
import com.zyd.module.api.service.IVerifyCodeGen;
import com.zyd.module.api.service.impl.SimpleCharVerifyCodeGenImpl;
import com.zyd.module.api.vo.CustomerVo;
import com.zyd.module.api.vo.VerifyCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@CrossOrigin
@Api(tags = "主页")
@RestController
@RequestMapping("/index/customer")
public class CustomerEntityController {
    @Autowired
    private CustomerService customerService;

    @Autowired
    private RedisService redisService;

    @GetMapping("/insert/{num}")
    public R batchInsert(HttpServletRequest request,@PathVariable Integer num){
        String userIp = IpUtil.getIpAddr(request);
        Integer rate = getRate("rate:" + userIp,userIp);
        if (rate==null){
            redisService.set("rate:" + userIp,50);
            redisService.set("time:"+userIp,System.currentTimeMillis()+GlobalConstant.TEN_MINUTES);
        }

        for (int i = 0; i <num ; i++) {
                rate = getRate("rate:" + userIp,userIp);
                if (rate>0){
                CustomerEntity entity=new CustomerEntity();
                entity.setCusName(RandomUtils.randomName());
                entity.setCusEmail(RandomUtils.getEmail());
                entity.setAddress(RandomUtils.getAddress());
                entity.setCusPhone(RandomUtils.getPhoneNum());
                entity.setCusMsg("云原生是一种利用云计算交付模型的优势来构建和运行应用程序的方法论。当企业使用云原生架构开发和运维应用程序时，它们能更快速地响应客户需求将新想法推向市场。");
                entity.setProName("N95医用口罩,一次性普通型手术衣(AAMI 3级)");
                entity.setDelFlag(GlobalConstant.CUSTOMER_TRUE);
                customerService.save(entity);
                redisService.set("rate:" + userIp,(rate-1));
                }
                else if (rate<=0){
                    return R.error().data("msg","提交次数超过限制，请勿重复提交！");
                }
        }
        return R.ok().data("msg","success");
    }
   private Integer getRate(String key, String userIp){
       Long expires = redisService.get("time:" + userIp);
       if (expires==null){
           return null;
       }else {
           if (System.currentTimeMillis()>=expires){
               redisService.del("time:" + userIp);
               redisService.del(key);
               return null;
           }else {
               return redisService.get(key);
           }
       }
   }

    //前端参考check.html
    @ApiOperation(value = "验证码")
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse response,@RequestParam("time") String time) {
        IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
        try {
            //设置长宽
            VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
            String user_ip= IpUtil.getIpAddr(request);
            redisService.del("code:"+user_ip);
            String code = verifyCode.getCode();

            log.info("验证码是："+code);
            //将验证码放到Redis里面
            redisService.set("code:"+user_ip,code);
            //设置响应头
            response.setHeader("Pragma", "no-cache");
            //设置响应头
            response.setHeader("Cache-Control", "no-cache");
            //在代理服务器端防止缓冲
            response.setDateHeader("Expires", 0);
            //设置响应内容类型
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    @ApiOperation("提交客户信息")
    @PostMapping("/submitConsumerInfos")
    public R submitConsumerInfos(HttpServletRequest request,@RequestBody CustomerVo customerVo){
        String userIp=IpUtil.getIpAddr(request);
        if (customerVo.getCode()==null||"".equals(customerVo.getCode())){
            return R.error().data("msg","验证码为空");
        }else {
            String code = (String)redisService.get("code:" + userIp);
            if (!code.equals(customerVo.getCode())){
                return R.error().data("msg","验证码错误");
            }
        }
        Integer rate = getRate("rate:" + userIp,userIp);
        if (rate==null){
            redisService.set("rate:" + userIp,50);
            redisService.set("time:"+userIp,System.currentTimeMillis()+GlobalConstant.TEN_MINUTES);
        }
        rate = getRate("rate:" + userIp,userIp);
        if (rate>0){
            CustomerEntity customer=new CustomerEntity();
            customer.setCusName(customerVo.getCusName());
            customer.setCusEmail(customerVo.getCusEmail());
            customer.setCusPhone(customerVo.getCusPhone());
            customer.setCusMsg(customerVo.getCusMsg());
            customer.setProName(customerVo.getProName()==null?"":customerVo.getProName());
            customer.setAddress(customerVo.getAddress()==null?"":customerVo.getAddress());
            customer.setDelFlag(GlobalConstant.CUSTOMER_TRUE);
            boolean flag = customerService.save(customer);
            redisService.del("code:"+userIp);
            if (flag){
                redisService.set("rate:" + userIp,(rate-1));
                return R.ok().data("msg","success");
            }else {
                return R.error().data("msg","failed");
            }
        }
        else if (rate<=0){
            return R.error().data("msg","提交次数超过限制，请勿重复提交！");
        }else {
            return R.error().data("msg","failed");
        }
    }
}
